package jp.co.systemi.asp.workflow.webservice;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.data.PaidHoliday;
import jp.co.systemi.asp.workflow.peer.PaidHolidayPeer;

import org.apache.wicket.PageParameters;
import org.apache.wicket.model.Model;
import org.datanucleus.util.StringUtils;

public class PaidHolidayInfos extends WebServicePage {
    private static final Logger log = Logger.getLogger(PaidHolidayInfos.class
            .getName());
    @SuppressWarnings("unchecked")
    public PaidHolidayInfos(PageParameters pars) {
        String month = pars.getString("month");
        Calendar prevMonthCal = Calendar.getInstance();
        if(!StringUtils.isEmpty(month)){

            // 画面からのリクエスト
            if (!month.matches("(\\d{4,4})(\\d{2,2})")) {
                log.info("パラメータエラー");
                setDefaultModel(new Model(new Exception("parameter error")));
                return;
            }
            prevMonthCal.set(Calendar.YEAR, Integer.parseInt(month.substring(
                    0, 4)));
            prevMonthCal.set(Calendar.MONTH, Integer.parseInt(month.substring(
                    4, 6)) - 1);
        }
        else {
            // 自動の場合は
            // このタスクは毎月の1日に動くとして、前月の休暇状況を取得する
            prevMonthCal.add(Calendar.DATE, -1);
        }
        List<PaidHoliday> holidays = PaidHolidayPeer.getPaidHolidayData(prevMonthCal.getTime());
        Integer id = pars.getAsInteger("id");
        if (id == null) {
            setDefaultModel(new Model((Serializable) holidays));
            return;
        }
        for(PaidHoliday holiday : holidays){
            if(id.intValue() == holiday.getSeq().intValue()){
                ArrayList<PaidHoliday> a = new ArrayList<PaidHoliday>();
                a.add(holiday);
                setDefaultModel(new Model(a));
                return;
            }
        }
        setDefaultModel(new Model(new Exception("data not found")));
    }
    protected String getXML(){
        String templateVm = this.getClass().getPackage().getName().replace(".", "/") + "/PaidHolidayInfos.vm";
        Map<String, Object> vars = new HashMap<String, Object>();
        if(getDefaultModel().getObject() instanceof Exception){
            vars.put("error", getDefaultModel().getObject());
            templateVm = this.getClass().getPackage().getName().replace(".", "/") + "/error.vm";
            String msgBody = jp.co.systemi.asp.utils.StringUtils.mergeTemplate(templateVm, vars);
            return msgBody;
        }
        vars.put("holidays", getDefaultModel().getObject());
        String msgBody = jp.co.systemi.asp.utils.StringUtils.mergeTemplate(templateVm, vars);
        return msgBody;
    }
}
